import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Button,
  Divider,
  Row,
  Col,
  Input,
  Select,
  Spin,
  message,
  Tag,
  Empty,
} from 'antd';
import { connect } from 'dva';
import { useBoolean } from '@umijs/hooks';
import cloneDeep from 'lodash/cloneDeep';
import PubSub from 'pubsub-js';
import request from '@/utils/request';
import FooterToolbar from '@/components/FooterToolbar';
import SlickTable from '@/components/SlickTable';
import AddConfigRow from './AddConfigRow';
import SelectForm from './SelectForm';
import SelectMember from './SelectMember';
import styles from '../index.less';

function AddStatusFlow({ size: { height }, form, goToStep, obj, linkRefresh }) {
  const { getFieldDecorator } = form;

  const [dataSource, setDataSource] = useState([]);
  const { state, setTrue, setFalse } = useBoolean(false);
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState([[], [], []]);
  const [butLoding, setButLoding] = useState(false);

  const [deleteArr, setDeleteArr] = useState([]);
  const { state: formState, setTrue: setFormTrue, setFalse: setFormFalse } = useBoolean(false);
  const [visiable, setVisiable] = useState(true);

  const { state: memberState, setTrue: setMemberTrue, setFalse: setMemberFalse } = useBoolean(
    false
  );

  const [sysUserCOList, setSysUserCOList] = useState([]);

  async function init() {
    setLoading(true);
    await Promise.all([
      request('pmc/pms/PmOrderFlowNodeController/getConfig', {
        method: 'GET',
        data: {
          flowNodeId: obj.flowNodeId,
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'PmOrderFlowNode',
          attrNbr: 'operMode',
        },
      }),
      request('pmc/pms/StaticDataController/getStaticAttr.do', {
        data: {
          busiObjNbr: 'PmOrderFlowNode',
          attrNbr: 'orderState',
        },
      }),
    ])
      .then(res => {
        setResult(res);
        form.setFieldsValue({
          flowNodeName: res[0].data.pmOrderFlowNodeCO
            ? res[0].data.pmOrderFlowNodeCO.flowNodeName
            : '',
          flowNodeCode: res[0].data.pmOrderFlowNodeCO
            ? res[0].data.pmOrderFlowNodeCO.flowNodeCode
            : '',
          flowName: res[0].data.pmOrderFlowNodeCO ? res[0].data.pmOrderFlowNodeCO.flowName : '',
          operMode: res[0].data.pmOrderFlowNodeCO ? res[0].data.pmOrderFlowNodeCO.operMode : '',
          orderState: res[0].data.pmOrderFlowNodeCO ? res[0].data.pmOrderFlowNodeCO.orderState : '',
        });

        // 关联表单数据填充
        if (res[0].data.pmTacheFormRelaCO) {
          form.setFieldsValue({
            formId: res[0].data.pmTacheFormRelaCO ? res[0].data.pmTacheFormRelaCO.formId : '',
            formName: res[0].data.pmTacheFormRelaCO ? res[0].data.pmTacheFormRelaCO.formName : '',
            formVersionNbr: res[0].data.pmTacheFormRelaCO
              ? res[0].data.pmTacheFormRelaCO.formVersionNbr
              : '',
            tacheFormRelId: res[0].data.pmTacheFormRelaCO
              ? res[0].data.pmTacheFormRelaCO.tacheFormRelId
              : '',
          });
        } else {
          setVisiable(false);
        }

        // 环节成员列表数据填充
        if (Array.isArray(res[0].data.sysUserCOList)) {
          setSysUserCOList(res[0].data.sysUserCOList);
        }

        if (res[0].data.pmTachePlanRelaCOList && res[0].data.pmTachePlanRelaCOList.length > 0) {
          const arr = [];
          res[0].data.pmTachePlanRelaCOList.map((item, index) => {
            arr.push({ ...item, tableId: index });
          });
          setDataSource(arr);
        }
      })
      .finally(() => setLoading(false));
  }
  useEffect(() => {
    init();
  }, []);

  const callBack = value => {
    const data = cloneDeep(dataSource);
    data.push({
      ...value,
      /* eslint-disable */
      tableId:
        Math.max.apply(
          Math,
          dataSource.map(function(o) {
            return o.tableId;
          })
        ) === -Infinity
          ? 0
          : Math.max.apply(
              Math,
              dataSource.map(function(o) {
                return o.tableId;
              })
            ) + 1,
      /* eslint-enable */
    });
    setDataSource(data);
  };

  const onClose = () => {
    setVisiable(false);
  };

  const onMemberClose = (e, record) => {
    // console.log(record);
    e.preventDefault();
    const arr = cloneDeep(sysUserCOList);
    arr.splice(
      arr.findIndex(itt => itt.userId === record.userId),
      1
    );

    setSysUserCOList(arr);
  };

  const formCallBack = value => {
    if (visiable === false) {
      setVisiable(true);
    }
    form.setFieldsValue({
      formId: value[0].formVersionId,
      formName: value[0].formName,
      formVersionNbr: value[0].formVersionNbr,
      tacheFormRelId: '',
    });
  };

  const memberCallBack = value => {
    setSysUserCOList(value);
  };

  const onSubmit = () => {
    form.validateFields((err, value) => {
      if (err) return;
      // console.log(value, dataSource, deleteArr);
      setButLoding(true);
      request('pmc/pms/PmOrderFlowNodeController/updateConfig', {
        data: {
          pmOrderFlowNodeCO: {
            flowNodeName: value.flowNodeName,
            flowNodeCode: value.flowNodeCode,
            flowName: value.flowName,
            flowNodeId: obj.flowNodeId,
            operMode: value.operMode,
            orderState: value.orderState,
          },
          pmTacheFormRelaCO:
            visiable === false
              ? null
              : {
                  formId: value.formId,
                  formName: value.formName,
                  formVersionNbr: value.formVersionNbr,
                  tacheFormRelId: value.tacheFormRelId,
                },

          sysUserCOList,

          pmTachePlanRelaCOList: dataSource,
          delTachePlanRelIdList: deleteArr,
        },
      })
        .then(res => {
          if (res.success) {
            message.success('提交成功！');
            linkRefresh();
            goToStep(1);
          } else {
            message.error(res.errMessage);
          }
        })
        .always(() => {
          setButLoding(false);
        });
    });
  };

  return (
    <div>
      <Card
        title={obj.operType === 'config' ? '环节拓展配置' : '环节拓展配置详情'}
        style={{ minHeight: height, paddingBottom: 40 }}
      >
        <Spin spinning={loading}>
          <Form className="flow fix-label padding-bottom">
            <div className="ant-detail-title">环节信息</div>
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="环节名称">
                  {getFieldDecorator('flowNodeName', {
                    rules: [
                      {
                        required: true,
                        message: '环节名称不能为空',
                      },
                    ],
                  })(<Input allowClear placeholder="请输入" disabled />)}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="环节编码">
                  {getFieldDecorator('flowNodeCode', {
                    rules: [
                      {
                        required: true,
                        message: '流程编码不能为空',
                      },
                    ],
                  })(<Input allowClear placeholder="请输入" disabled />)}
                </Form.Item>
              </Col>
              {/* <Col span={6}>
                <Form.Item label="流程类型">
                  {getFieldDecorator('processType')(
                    <Input allowClear placeholder="请输入" disabled />
                  )}
                </Form.Item>
              </Col> */}
              <Col span={6}>
                <Form.Item label="所属流程">
                  {getFieldDecorator('flowName', {
                    rules: [
                      {
                        required: true,
                        message: '流程名称不能为空',
                      },
                    ],
                  })(<Input allowClear placeholder="请输入" disabled />)}
                </Form.Item>
              </Col>
            </Row>
            <Divider className="small" />
            <div className="ant-detail-title">环节拓展配置</div>
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item label="处理模式">
                  {getFieldDecorator('operMode', {
                    rules: [
                      {
                        required: true,
                        message: '处理模式不能为空',
                      },
                    ],
                  })(
                    <Select
                      allowClear
                      placeholder="请选择"
                      disabled={obj.operType === 'detail' ? true : false}
                    >
                      {result[1].map(item => {
                        return (
                          <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                        );
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="工单状态">
                  {getFieldDecorator('orderState')(
                    <Select
                      allowClear
                      placeholder="请选择"
                      disabled={obj.operType === 'detail' ? true : false}
                    >
                      {result[2].map(item => {
                        return (
                          <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                        );
                      })}
                    </Select>
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Divider className="small" />
            <div className="ant-detail-title">
              <span>关联表单</span>
              {obj.operType === 'detail' ? null : (
                <Button type="primary" className="pull-right" onClick={setFormTrue}>
                  选择
                </Button>
              )}
            </div>
            <Tag
              closable={obj.operType === 'detail' ? false : true}
              color="geekblue"
              className={styles.link_expand}
              onClose={onClose}
              visible={visiable}
            >
              <Row gutter={16}>
                <Col hidden span={6}>
                  <Form.Item label="表单ID">
                    {getFieldDecorator('formId')(<Input disabled placeholder="请输入" />)}
                  </Form.Item>
                </Col>
                <Col hidden span={6}>
                  <Form.Item label="表单tacheFormRelId">
                    {getFieldDecorator('tacheFormRelId')(<Input disabled placeholder="请输入" />)}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="表单名称">
                    {getFieldDecorator('formName')(<Input disabled placeholder="请输入" />)}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="表单版本">
                    {getFieldDecorator('formVersionNbr')(<Input disabled placeholder="请输入" />)}
                  </Form.Item>
                </Col>
              </Row>
            </Tag>
            {visiable === false ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> : null}

            <Divider className="small" />
            <div className="ant-detail-title">
              <span>环节成员列表</span>
              {obj.operType === 'detail' ? null : (
                <Button type="primary" className="pull-right" onClick={setMemberTrue}>
                  选择
                </Button>
              )}
            </div>
            {sysUserCOList.length ? (
              sysUserCOList.map(item => (
                <Tag
                  closable={obj.operType === 'detail' ? false : true}
                  color="geekblue"
                  className={styles.link_expand}
                  onClose={e => {
                    onMemberClose(e, item);
                  }}
                >
                  <Row gutter={16}>
                    <Col span={6}>
                      <Form.Item label="用户编码">
                        <Input disabled placeholder="请输入" value={item.userCode} />
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Form.Item label="用户名称">
                        <Input disabled placeholder="请输入" value={item.userName} />
                      </Form.Item>
                    </Col>
                  </Row>
                </Tag>
              ))
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </Form>
        </Spin>

        <Divider className="small" />
        <div className="ant-detail-title">
          <span>事件设置</span>
          {obj.operType === 'config' ? (
            <Button type="primary" className="pull-right" onClick={setTrue}>
              新增设置
            </Button>
          ) : null}
        </div>
        <SlickTable
          style={{ marginTop: 8 }}
          rowKey={record => record.tableId}
          pagination={false}
          dataSource={dataSource}
          columns={[
            {
              title: '关联事件',
              dataIndex: 'eventTypeName',
              ellipsis: true,
            },
            {
              title: '完成时限',
              dataIndex: 'alertValue',
              ellipsis: true,
            },
            {
              title: '告警时限',
              dataIndex: 'limitValue',
              ellipsis: true,
            },
            {
              title: '时间单位',
              dataIndex: 'timeUnitName',
              ellipsis: true,
            },
            {
              title: '关联方案',
              dataIndex: 'planName',
              ellipsis: true,
            },
            {
              title: '操作',
              align: 'center',
              width: 100,
              render: (text, record) => {
                return obj.operType === 'config' ? (
                  <span>
                    <a
                      onClick={() => {
                        const arr = cloneDeep(dataSource);
                        arr.map((item, index) => {
                          if (item.tableId === record.tableId) {
                            arr.splice(index, 1);
                            deleteArr.push(item.tachePlanRelId);
                            setDeleteArr(deleteArr);
                          }
                        });
                        setDataSource(arr);
                      }}
                    >
                      删除
                    </a>
                  </span>
                ) : null;
              },
            },
          ]}
        />
      </Card>
      <FooterToolbar>
        {obj.operType === 'config' ? (
          <Button type="primary" onClick={onSubmit} loading={butLoding}>
            确定
          </Button>
        ) : null}
        <Button type="default" onClick={() => goToStep(1)}>
          返回
        </Button>
      </FooterToolbar>
      {state ? <AddConfigRow visiable={state} close={setFalse} callback={callBack} /> : null}
      {formState ? (
        <SelectForm visiable={formState} close={setFormFalse} callback={formCallBack} />
      ) : null}
      {memberState ? (
        <SelectMember
          visiable={memberState}
          close={setMemberFalse}
          callback={memberCallBack}
          memberCheck={sysUserCOList}
        />
      ) : null}
    </div>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(AddStatusFlow));
